import { createRouter, createWebHistory } from 'vue-router';
import { verifykey } from '@/api/verify';

const router = createRouter({
    // HTML5模式
    history: createWebHistory(import.meta.env.BASE_URL),
    routes: [
        {
            path: '/',
            component: () => import('@/components/userlist/UserList.vue'),
            name: 'userList',
            meta: {
                requireAuth: true,
            },
        },
        {
            path: '/ChatPage',
            component: () => import('@/components/chatwindow/ChatPage.vue'),
            name: 'chatPage',
            meta: {
                // 跳转页面需不需要验证
                requireAuth: true,
            },
        },
        {
            path: '/error',
            component: () => import('@/pages/ChangPage.vue'),
            name: 'error',
            meta: {
                requireAuth: false,
            },
        },
        {
            path: '/Aipage',
            component: () => import('@/pages/Aipage.vue'),
            name: 'ai',
            meta: {
                requireAuth: true,
            },
        },
    ],
});

// 全局路由守卫 每次导航都会触发，解析守卫刚好会在导航被确认之前、所有组件内守卫和异步路由组件被解析之后调用
// router.beforeResolve;

router.beforeResolve(async (to, _, next) => {
    // 要去的路由
    if (to.meta.requireAuth) {
        const keys = Object.keys(to.query);
        if (keys.length === 1) {
            if (await verifykey(keys[0])) {
                next();
            }
            // 如果用户未能验证身份，则 `next` 会被调用两次
        } else next({ name: 'error' });
        // 如果用户未能验证身份，则 `next` 会被调用两次
    } else next();
});

export default router;
